// pages/car/car.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 商品数据
    carList: [],
    totalData: 0, //总价格
    // 全选
    checkedAll: false,
    // 选择数组
    checkList: [],
    orderNum: 0, // 选择单数
  },

  // 减商品数量
  sub(event) {
    let index = event.target.dataset.index;
    let num = this.data.carList[index].num;
    let key = "carList[" + index + "].num";
    num = num <= 1 ? 1 : num - 1;
    this.setData({
      [key]: num
    })
    this.getTotalOne()
  },
  // 减商品数量
  add(event) {
    let index = event.target.dataset.index;
    this.data.carList[index].num += 1;
    this.setData({
      carList: this.data.carList
    })
    this.getTotalOne()
  },
  // 计算总价格
  getTotal() {
    let carList = this.data.carList;
    if (!carList) {
      return;
    }
    let data = carList.reduce((total, item) => {
      console.log(total, item);
      return total + item.num * item.goodsPrice
    }, 0)
    this.setData({
      totalData: data
    })
  },
  // 计算选择的商品的价格
  getTotalOne() {
    let carlist = this.data.carList;
    let data = 0;
    if (!carlist) {
      return;
    }
    // 循环列表，如果选择的话就把价钱加上去。否则就跳过
    carlist.forEach(item => {
      // console.log(item);
      if (!item.checked) {
        return;
      }
      // 计算选中价格
      data += item.num * item.goodsPrice
    })
    this.setData({
      totalData: data
    })
  },

  // 删除
  del(event) {
    let index = event.target.dataset.index;
    let checklist = this.data.checkList;
    let carlist = this.data.carList;

    carlist.splice(index, 1);
    checklist.splice(index, 1)

    wx.setStorageSync('goodsCarList', carlist)

    this.setData({
      carList: carlist,
      checkList: checklist,
      // totalData: data
    })
    this.data.checkedAll = this.data.checkList.length == this.data.carList.length

    this.getTotalOne()
  },
  // 选中
  checkHandler(e) {
    // console.log(e);
    let index = e.currentTarget.dataset.index;
    let index2 = e.detail.value[0];
    let checklist = this.data.checkList;
    let carlist = this.data.carList;
    let onum = this.data.orderNum;
    // 判断是否有勾选，有就放进去
    // console.log(index2,index);
    if (index2) {
      checklist.push(index2);
      // console.log(checklist);
      carlist[index2].checked = true;
      onum++;
    } else { // 如果没有的话就把对应的下标删掉。
      carlist[index].checked = false;
      checklist.splice(index, 1)
      console.log(carlist, checklist);
      onum--;
    }
    this.data.checkedAll = this.data.checkList.length == this.data.carList.length
    // 单选的总价
    this.getTotalOne()
    this.setData({
      checkList: checklist,
      checkedAll: this.data.checkedAll,
      carList: carlist,
      orderNum: onum
    })


  },


  // 全选按钮
  changeCheckAll(e) {
    let checkedAll = this.data.checkedAll;
    // 获取商品列表
    let carlist = this.data.carList
    checkedAll = !checkedAll;
    // 遍历循环
    carlist.forEach(cart => {
      cart.checked = checkedAll
    })

    // 总价
    this.getTotal()
    if (!checkedAll) {
      this.data.totalData = 0;
    }
    this.setData({
      orderNum: carlist.length,
      carList: carlist,
      checkedAll: checkedAll,
      totalData: this.data.totalData
    })
  },

  // 跳转支付页面
  goOrder() {

    let userinfo = wx.getStorageSync('userinfo'); // 获取用户信息
    let carlist = this.data.carList; // 购物车数组
    let checklist = this.data.checkList; // 选择的数组
    let paylist = []
    // 如果没有选中商品的话就提醒用户
    if (checklist.length < 1) {
      wx.showToast({
        title: '请先选择商品',
        icon: 'error',
        duration: 2000 //持续的时间
      })
      return;
    }

    carlist.forEach((item, index) => {
      if (item.checked) {
        paylist.push(item)
      }
    })
    wx.setStorageSync('paylist', paylist);


    wx.setStorageSync('goodsCarList', this.data.carList)

    this.setData({
      carList: carlist,
      checkList: []
    })

    // 判断是否登录
    if (userinfo) {
      // 保留当前页面，跳转到应用内的某个页面。
      wx.navigateTo({
        url: '/pages/pay/pay',
      })
    } else {
      // 提示
      wx.showToast({
        title: '请登录',
        icon: 'none',
        duration: 3000,
        success() {
          // 跳转到 tabBar 页面，并关闭其他所有非 tabBar 页面
          setTimeout(() => {
            wx.switchTab({
              url: '/pages/my/my',
            })
          }, 3000)
        }
      })

    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

    // 获取缓存数据
    let goodsCarList = wx.getStorageSync('goodsCarList');
    console.log(goodsCarList);

    this.setData({
      carList: goodsCarList,
      totalData: 0,
      orderNum: 0
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    // console.log(this);
    if (this.data.carList) {
      this.data.carList.forEach(item => {
        item.checked = false
      })
    }

    wx.setStorageSync('goodsCarList', this.data.carList)


    this.setData({
      checkList:[],
      checkedAll: false,
      orderNum: 0,
    })

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})